/*NOTICE

This software was produced for the U. S. Government
under Contract No. FA8721-09-C-0002, and is
subject to the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation Clause
(DFARS) 252.227-7014 (JUN 1995)

(c) 2009 The MITRE Corporation. All Rights Reserved.
*/
package org.mitre.xmltransform.wsdloperation2txt;

import java.io.File;
import java.util.List;

import org.mitre.xmltransform.transform.Transform;
import org.mitre.xmltransform.txt.TxtOutputDocument;
import org.mitre.xmltransform.wsdl.WsdlInputDocument;

public class WsdlOperation2TxtTransform extends Transform {

	@Override
	public void initialize(File pInputFile, File pOutputFile) {
		mInput = new WsdlInputDocument(pInputFile);
		mOutput = new TxtOutputDocument(pOutputFile);
	}
	
	public int setArguments(String[] pTransformArguments) {
		// expects 3 or 4 arguments
		if (pTransformArguments == null || pTransformArguments.length < 3 || pTransformArguments.length > 4) {
			return SETARGS_BAD_ARGUMENT_COUNT;
		}
		mNamespaceName = pTransformArguments[0];
		mPortTypeName = pTransformArguments[1];
		mOperationName = pTransformArguments[2];
		if (pTransformArguments.length == 4) {
			mDirection = pTransformArguments[3];
		} else {
			mDirection = null;
		}
		return SETARGS_NO_ERROR;		
	}

	public String getUsageMessage() {
		String result = super.getUsageMessage();
		result += " < namespace > < port type > < operation >[ < inputs/outputs >]";
		return result;
	}

	@Override
	public void transform() {
		if (generateOutput()) {
			mOutput.finishDocument();
			mOutput.writeOutput();
		}		
	}

	private boolean generateOutput() {
		try {
			// inputs
			if (mDirection == null || mDirection.equals("inputs")) {
				List<WsdlInputDocument.ValueSpec> inputs = mInput.getOperationInputs(
						mNamespaceName, mPortTypeName, mOperationName);
				if (inputs == null) return false;
				for (WsdlInputDocument.ValueSpec item : inputs) {
					mOutput.addRecord(new String[] { "inputs", mOperationName, item.getPath(), item.getType() });
				}
			}
			if (mDirection == null || mDirection.equals("outputs")) {
				List<WsdlInputDocument.ValueSpec> outputs = mInput.getOperationOutputs(
						mNamespaceName, mPortTypeName, mOperationName);
				if (outputs == null) return false;
				for (WsdlInputDocument.ValueSpec item : outputs) {
					mOutput.addRecord(new String[] { "outputs", mOperationName, item.getPath(), item.getType() });
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private String mNamespaceName, mPortTypeName, mOperationName, mDirection;
	private WsdlInputDocument mInput;
	private TxtOutputDocument mOutput;
}
